package com.hong610.net.http.client;

import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.InputStream;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * HTTPS HttpClient
 * Created by Hong on 2016/12/31.
 */
public class SSLClient {

    public static CloseableHttpClient createSSLDefault() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {

        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        }).build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
        return HttpClientBuilder.create().setSSLSocketFactory(sslsf).build();
    }

    public static CloseableHttpClient createSSLCret(String cretPath, char[] password) throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException, IOException, CertificateException, UnrecoverableKeyException {

        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        InputStream is = SSLClient.class.getClassLoader().getResourceAsStream(cretPath);// 读取证书
        try {
            keyStore.load(is, password);
        } finally {
            is.close();
        }

        SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadKeyMaterial(keyStore, password);
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContextBuilder.build(), new String[]{"TLSv1"}, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        return HttpClientBuilder.create().setSSLSocketFactory(sslsf).build();
    }
}
